# -*- coding: utf-8-*-
from openerp.osv import osv
from openerp.osv import fields
import re


class res_partner(osv.osv):
    _inherit = 'res.partner'

    def name_get(self, cr, uid, ids, context=None):
        """根据partner表上字段的设置， 判断partner 类型"""
        res = []
        for contacts_ini in self.browse(cr, uid, ids, context=context):
            if not contacts_ini.is_company and contacts_ini.contacts and contacts_ini.mobile:
                res.append((contacts_ini.id, contacts_ini.name +
                            "(" + str(contacts_ini.mobile) + ")"))
            elif contacts_ini.supplier:
                res.append((contacts_ini.id, contacts_ini.name +
                            "(" + str(contacts_ini.supplier_code) + ")"))
            else:
                res.append((contacts_ini.id, contacts_ini.name))
        return res

    def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
        """扩大 name search 的范围，允许按照用户编号进行搜索"""
        args = args or []
        if context.get("default_contacts_search") and name:
            contacts_ids = self.search(cr, uid, ["|", ('mobile', 'ilike', name), ('name', operator, name)] + args, limit=limit, context=context or {})
            return self.name_get(cr, uid, contacts_ids, context=context)
        if name:
            if not cmp(args, [['supplier', '=', True]]) and name.isdigit():
                ids = self.search(cr, uid, [('supplier_code', operator, name)] + args, limit=limit, context=context or {})
            else:
                ids = self.search(cr, uid, [('name', operator, name)] + args, limit=limit, context=context or {})
            res = []
            if not ids and '(' in name:
                names = name.split('(')
                ids = self.search(cr, uid, ["|", ('supplier_code', 'ilike', names[1][0:-1]), ('supplier', '=', True), ('name', operator, names[0])] + args, limit=limit, context=context or {})
            for contacts_ini in self.browse(cr, uid, ids, context=context):
                res.append(contacts_ini.id)
            return self.name_get(cr, uid, res, context=context)
        return super(res_partner, self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)

    def _get_is_inauguratory(self, cr, uid, ids, field_name, arg, context=None):
        """计算字段判断用户是否在职"""
        res = {}
        for partner in self.browse(cr, uid, ids, context=context):
            if partner.contacts and any(contacts.is_inauguratory for contacts in partner.company_contacts_ids):
                res[partner.id] = True
            else:
                res[partner.id] = False

        return res

    def _check_mobile_length(self, cr, uid, ids, context=None):
        """校验手机号的位数"""
        for partner in self.browse(cr, uid, ids, context=context):
            if not partner.mobile:
                return True
            if partner.mobile and partner.contacts and len(partner.mobile) != 11:
                return False
            if not re.match('^[0-9]+$', partner.mobile):
                return False
        return True

    def _check_mobile(self, cr, uid, ids, context=None):
        """判断手机号是否存在，一个手机号只能对应一个联系人"""
        for partner in self.browse(cr, uid, ids, context=context):
            if not partner.mobile:
                return True
            if partner.contacts:
                contacts_ids = self.search(cr, uid, [('mobile', '=', partner.mobile),
                                                     ('contacts', '=', True), ('id', '!=', partner.id)], context=context)
                if contacts_ids:
                    return False

        return True

    def _check_supplier_code(self, cr, uid, ids, context=None):
        """供应商代码必须唯一判定！"""
        for partner in self.browse(cr, uid, ids, context=context):
            if not partner.supplier_code:
                return True

            contacts_ids = self.search(cr, uid, [('supplier_code', '=', partner.supplier_code),
                                                 ('supplier', '=', True), ('id', '!=', partner.id)], context=context)
            if contacts_ids:
                return False

        return True

    def write(self, cr, uid, ids, vals, context=None):
        if vals.get('main_contacts') and not context.get('refresh_main_contacts'):
            for partner_id in ids:
                self.refresh_main_contacts(cr, uid, partner_id, vals.get('main_contacts'), context=context)
        # 默认收货地址，收货地址中的联系人默认地址打勾
        # if vals.get('principal') and not context.get('refresh_principal'):
        #     for partner_id in ids:
        #         self.refresh_principal(cr, uid, partner_id, vals.get('principal'), context=context)
        #         adress_objs = self.pool.get('customer.address').browse(cr, uid, vals.get('principal'), context=context)
        #         partner = self.browse(cr, uid, partner_id, context=context)
        #         if partner.supplier and not partner.customer:
        #             vals.update({'phone': adress_objs.phone_number or "", 'mobile': adress_objs.mobile_number or "",
        #                          'fax': adress_objs.fax or "", 'zip': adress_objs.zip or "", 'province_id': adress_objs.province_id.id or "", 'street': adress_objs.street or "",
        #                          'city_id': adress_objs.city_id.id or "", 'county_id': adress_objs.county_id.id or "", 'title': adress_objs.title.id or ""})
        before_contacts = []
        after_contacts = []
        for partner in self.browse(cr, uid, ids, context=context):
            if not partner.contacts:
                for contact in partner.child_contacts_ids:
                    before_contacts.append(contact.contacts_id)

        # 新建企业客户时联系人写入parent_id时，需要把父级的user_id和share_to_uid带过来
        parent_id = vals.get('parent_id', None)
        if parent_id:
            parent_partner_row = self.browse(cr, uid, parent_id, context=context)
            vals.update({'user_id': parent_partner_row.user_id.id, 'share_to_uid': parent_partner_row.share_to_uid.id})

        super(res_partner, self).write(cr, uid, ids, vals, context=context)
        for partner in self.browse(cr, uid, ids, context=context):
            if vals.get('user_id', 'default_flag') != 'default_flag' or vals.get('share_to_uid', 'default_flag') != 'default_flag':
                if partner.child_contacts_ids:
                    for contacts in partner.child_contacts_ids:
                        if vals.get('user_id', 'default_flag') != 'default_flag':
                            contacts.contacts_id.write({'user_id': vals.get('user_id')})
                        if vals.get('share_to_uid', 'default_flag') != 'default_flag':
                            contacts.contacts_id.write({'share_to_uid': vals.get('share_to_uid')})

            if not partner.contacts:
                for contact in partner.child_contacts_ids:
                    after_contacts.append(contact.contacts_id)

            if partner.contacts:
                for contacts in (contacts for contacts in partner.company_contacts_ids if contacts.is_main_contacts):
                    contacts.refresh_main_contacts()
            if vals.get('purchase_default_contact_id'):
                partner.purchase_default_contact_id.write({'default': True})
        # if before_contacts != after_contacts and len(before_contacts) == len(after_contacts):
        #  #感觉逻辑上还有问题，文字上也有问题，看不懂 应该是遗留问题。
        #     for contacts_ini in before_contacts:
        #         if contacts_ini not in after_contacts:
        #             raise osv.except_osv(u'错误', u'您不能修改已存在的重要联系人。如需更改，\
        #                                         可以再新建一个重要联系人然后删除需要修改的联系人')
        return True

    def refresh_principal(self, cr, uid, partner_id, principal_id, context=None):
        """以前"""
        if partner_id and principal_id:
            for principal in self.browse(cr, uid, partner_id, context=context).multi_address_ids:
                principal.write({'default': principal.id == principal_id})

        return True

    def refresh_main_contacts(self, cr, uid, partner_id, contacts_id, context=None):
        context = context or {}
        if partner_id and contacts_id:
            context = dict({'refresh_main_contacts': True}, **context)
            contacts = self.pool.get('company.contacts').browse(
                cr, uid, contacts_id, context=context)
            partner = self.browse(cr, uid, partner_id, context=context)

            partner.write({'main_contacts': contacts_id})
            contacts.refresh_main_contacts()

            for contacts in partner.child_contacts_ids:
                contacts.write({'is_main_contacts': contacts.id == contacts_id})

        return True

    def _get_partner_from_contacts(self, cr, uid, ids, context=None):
        return list(set(contacts.contacts_id.id for contacts in self.browse(cr, uid, ids, context=context)))

    def get_real_contacts_ids(self, cr, uid, ids, context=None):
        for partner in self.browse(cr, uid, ids, context=context):
            for contacts in partner.child_contacts_ids:
                yield contacts.contacts_id

    def onchange_user_id(self, cr, uid, ids, user_id, context=None):
        """没啥用"""
        # 当客户修改销售员时，同时修改联系人company.contacts表对应的res.partner里的销售员为相同值\
        # for partner in self.browse(cr, uid, ids, context=context):
        #     for contacts in partner.child_contacts_ids:
        #         for contacts_partner in contacts.contacts_id:
        #             self.pool.get('res.partner').write(cr, uid, contacts_partner.id, {'user_id': user_id}, context=context)
        return {}

    _columns = {
        'weixinid': fields.char(u'微信号'),
        'contacts': fields.boolean(u'联系人'),
        'is_inauguratory': fields.function(_get_is_inauguratory, type='boolean', string=u'在职', store={
            'res.partner': (lambda self, cr, uid, ids, ctx=None: ids, ['company_contacts_ids'], 10),
            'company.contacts': (_get_partner_from_contacts, ['is_inauguratory'], 10),
        }),
        'company_contacts_ids': fields.one2many('company.contacts', 'contacts_id', u'联系人', domain=[('is_inauguratory', '=', True)]),
        'child_contacts_ids': fields.one2many('company.contacts', 'partner_id', u'就职记录', domain=[('is_inauguratory', '!=', False)]),
        'main_contacts': fields.many2one('company.contacts', string=u'主联系人'),
    }

    def unlink(self, cr, uid, ids, context=None):
        """只有把本公司的联系人离职了，才能够删除公司"""
        contacts_ids = self.pool.get('company.contacts').search(cr, uid,
                                                 [('contacts_id', 'in', ids)], context=context)
        if contacts_ids:
            raise osv.except_osv(u'警告',  u'存在就职记录不能删除!')
        return_vals = super(res_partner, self).unlink(cr, uid, ids, context=context)
        return return_vals

    _defaults = {
        'contacts': lambda self, cr, uid, ctx=None: ctx.get('contacts', False),
        # partne中的客户选项与联系人默认互斥
        'customer': lambda self, cr, uid, ctx=None: not ctx.get('contacts', False),
    }

    _constraints = [
        (_check_mobile, u'抱歉，联系人的手机号码不可以重复', ['contacts', 'mobile']),
        (_check_mobile_length, u'抱歉，联系人的手机号码必须是十一位数字', ['contacts', 'mobile']),
        (_check_supplier_code, u'抱歉，已经有相同的供应商代码存在！', ['supplier_code']),
    ]


class company_contacts(osv.osv):
    _name = 'company.contacts'
    _inherit = ['china.city.county']
    _order = 'is_main_contacts desc'
    _rec_name = "contacts_id"

    def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
        args = args or []
        result_list = []
        if name:
            super_list = super(company_contacts, self).name_search(cr, uid, name, args,
                                                                   operator=operator, context=context, limit=limit)
            if not super_list:
                result_list_id = self.pool.get('company.contacts'
                                               ).search(cr, uid, ['|', ('QQ', 'ilike', name), '|', ('phone', 'ilike', name), '|', ('mobile', 'ilike', name), '|',
                                                                  ('street', 'ilike', name), '|', ('weixinid', 'ilike', name), ('contacts_id', 'ilike', name)] + args, limit=limit, context=context or {})
                for customer_address_obj in self.browse(cr, uid, result_list_id, context=context or {}):
                    result_list.append(customer_address_obj.id)
                return self.name_get(cr, uid, result_list, context=context)
            return super_list
        return super(company_contacts, self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)

    def refresh_main_contacts(self, cr, uid, ids, context=None):
        for contacts in self.browse(cr, uid, ids, context=context):
            if contacts.partner_id.is_company:
                vals = {
                    'gender': contacts.contacts_id.gender,
                    'email': contacts.contacts_id.email,
                    'zip': contacts.contacts_id.zip,
                    'fax': contacts.contacts_id.fax,
                    'QQ': contacts.contacts_id.QQ,
                }
                vals.update({'mobile': contacts.contacts_id.mobile})
                vals.update({'phone': contacts.contacts_id.phone})
                vals.update({'street': contacts.contacts_id.street})
                vals.update({'county_id':contacts.contacts_id.county_id.id,
                             'province_id': contacts.contacts_id.province_id and contacts.contacts_id.province_id.id or False,
                             'city_id': contacts.contacts_id.city_id and contacts.contacts_id.city_id.id or False,
                             })
                contacts.partner_id.write(vals)

    def create(self, cr, uid, vals, context=None):
        # if not vals.get('mobile'):
        #     raise osv.except_osv(u'警告', u'请填写手机号！')
        # 同一联系人不能存在多条就职记录
        if vals.get('contacts_id') and vals.get('is_inauguratory'):
            contacts_ids = self.search(cr, uid, [('contacts_id', '=', vals.get('contacts_id')),
                                                 ('is_inauguratory', '=', True)], context=context)
            if contacts_ids:
                contacts_row = self.browse(cr, uid, contacts_ids[0], context=context)
                raise osv.except_osv(u'错误', u'同一联系人不能存在多条就职记录！(联系人 %s 有重复)'%(contacts_row.contacts_id.name))
        res_id = super(company_contacts, self).create(
            cr, uid, vals, context=context)
        contacts = self.browse(cr, uid, res_id, context=context)
        if vals.get('is_inauguratory', False):
            if contacts.contacts_id:
                self.pool.get('res.partner').write(cr, uid, contacts.contacts_id.id, {'mobile': vals.get('mobile'),
                                                                                      'gender': vals.get('gender'),
                                                                                      'phone': vals.get('phone'),
                                                                                      'email': vals.get('email'),
                                                                                      'street': vals.get('street'),
                                                                                      'zip': vals.get('zip'),
                                                                                      'fax': vals.get('fax'),
                                                                                      'QQ': vals.get('QQ'),
                                                                                      'province_id': vals.get('province_id'),
                                                                                      'city_id': vals.get('city_id'),
                                                                                      'county_id': vals.get('county_id'),
                                                                                      'comment': vals.get('comment')}, context=context)
            if contacts.partner_id:
                self.pool.get('res.partner').write(cr, uid, contacts.contacts_id.id, {'parent_id': contacts.partner_id.id}, context=context)

            # 暂时移除自动选中第一个联系人为主联系人的逻辑
            # if contacts.partner_id and (contacts.is_main_contacts or len(contacts.partner_id.child_contacts_ids) == 1):
            if contacts.partner_id and contacts.is_main_contacts:
                self.pool.get('res.partner').refresh_main_contacts(
                    cr, uid, contacts.partner_id.id, res_id, context=context)
        return res_id

    # def unlink(self, cr, uid, ids, context=None):
    #     partner_obj = self.pool.get('res.partner')
    # 删除记录时，清除parent_id字段
    #     for contacts_objs in self.browse(cr, uid, ids, context=context):
    #         partner_id = partner_obj.search(cr, uid, [('id', '=', contacts_objs.contacts_id.id), ('contacts', '=', True)], context=context)
    #         partner_obj.write(cr, uid, partner_id, {'parent_id': False, 'gender': '', 'phone': '', 'mobile': '', 'email': '',
    #                                                 'street': '', 'zip': '', 'province_id': '', 'city_id': '', 'county_id': ''}, context=context)

    #     return super(company_contacts, self).unlink(cr, uid, ids, context=context)

    def name_get(self, cr, uid, ids, context=None):
        """好像没实现啥功能"""
        res = []
        for contacts in self.browse(cr, uid, ids, context=context):
            res.append((contacts.id, contacts.contacts_id.name))

        return res

    #弹出联系人页面选择联系人时要把联系人的基本资料都带出来,否则保存时会把空值回写到联系人partner表
    def onchange_contacts_id(self, cr, uid, ids, contacts_id, context=None):
        #partner_id = self.pool.get('res.partner').search(cr, uid, [('id', '=', contacts_id)], context=context)
        partner = self.pool.get('res.partner').browse(cr, uid, contacts_id, context=context)
        value = {
            'mobile': partner.mobile,
            'province_id': partner.province_id,
            'city_id': partner.city_id,
            'county_id': partner.county_id,
            'street': partner.street,
            'zip': partner.zip,
            'phone': partner.phone,
            'email': partner.email,
            'QQ': partner.QQ,
            'fax': partner.fax,
            'gender': partner.gender,
            'comment': partner.comment
        }
        return {'value': value}

    # # 486 销售客户信息维护，主联系人手机变更同步企业信息
    # def onchange_mobile(self, cr, uid, ids, mobile, context=None):
    #     partner_obj = self.pool.get('res.partner')
    #     # for contacts in self.browse(cr, uid, ids, context=context):
    #     #     if contacts.is_main_contacts:
    #     #         partner_obj.write(cr, uid, contacts.partner_id.id, {'mobile': mobile}, context=context)
    #     return {'value': {'mobile': mobile}}

    def write(self, cr, uid, ids, vals, context=None):
        if not vals.get('is_inauguratory', True):
            partner_obj = self.pool.get('res.partner')
            vals.update({'is_main_contacts': False})
            for contacts_objs in self.browse(cr, uid, ids, context=context):
                partner_obj.write(cr, uid, contacts_objs.contacts_id.id, {'parent_id': False}, context=context)
                partner_objs = partner_obj.browse(cr, uid, contacts_objs.partner_id.id, context=context)
                partner_objs.write({'main_contacts': False, 'phone': '', 'mobile': '', 'email': '',
                                    'street': '', 'zip': '', 'province_id': '', 'city_id': '', 'county_id': ''})
                if not contacts_objs.contacts_id.mobile:
                    quit_partner_id = contacts_objs.contacts_id.id
                    self.unlink(cr, uid, contacts_objs.id, context=context)
                    ids.remove(contacts_objs.id)
                    # partner_objs.unlink()
                    partner_obj.unlink(cr, uid, [quit_partner_id], context=context)
        return super(company_contacts, self).write(cr, uid, ids, vals, context=context)

    def onchange_subscription_type(self, cr, uid, ids, subscription_type, mobile, context=None):
        # if subscription_type == '快递' and not mobile:
        #     return {'warning':
        #                 {'title': u'错误', 'message': u'没有填写手机号码，不能选择‘快递’位邮递方式！'},
        #             'value': {'subscription_type': False}}
        return True

    _columns = {
        'contacts_id': fields.many2one('res.partner', u'联系人', index=True),
        'partner_id': fields.many2one('res.partner', u'业务伙伴', index=True, ondelete='cascade'),
        'position': fields.char(u'职位'),
        'department': fields.char(u'部门'),
        'is_inauguratory': fields.boolean(u'在职'),
        'is_main_contacts': fields.boolean(u'主联系人'),
        'phone': fields.related('contacts_id', 'phone', type='char', string=u'电话'),
        'mobile': fields.related('contacts_id', 'mobile', type='char', string=u'手机'),
        'email': fields.related('contacts_id', 'email', type='char', string=u'邮箱'),
        'QQ': fields.related('contacts_id', 'QQ', type='char', string='QQ'),
        'gender': fields.related('contacts_id', 'gender', type='selection', selection=[(u'男', u'男'), (u'女', u'女')], string=u'性别'),
        'weixinid': fields.related('contacts_id', 'weixinid', type='char', string='微信号'),
        'fax': fields.related('contacts_id', 'fax', type='char', string='传真'),
        'zip': fields.related('contacts_id', 'zip', type='char', string='邮编'),
        'street': fields.related('contacts_id', 'street', type='char', string='街道'),
        'comment': fields.related('contacts_id', 'comment', type='text', string='备注'),
        'province_id': fields.related('contacts_id', 'province_id', type='many2one', relation="res.country.state", string='省'),
        'city_id': fields.related('contacts_id', 'city_id', type='many2one', relation="all.city", string='市'),
        'county_id': fields.related('contacts_id', 'county_id', type='many2one', relation="all.county", string='县'),
        'subscription_type': fields.selection([(u'邮政', u'邮政'), (u'快递', u'快递')], string='资料邮寄方式')

    }

    _sql_constraints = [
        ('contacts_id_uniq', 'CHECK(1=1)', u'不能建立相同的联系人'),
    ]
    _defaults = {
        'is_inauguratory': True,
        'partner_id': lambda self, cr, uid, ids, ctx=None: ctx.get('default_partner_id', False),
    }
